package adapter

import (
	"context"
	"fmt"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/mars/internal/admin/core/infrastructure/wxcloud"
	"github.com/mars/pkg/errors"
)

type DebugController struct {
}

// NewDebugController 创建调试控制器
func NewDebugController() *DebugController {
	return &DebugController{}
}

// QueryAllDataFromCollection 查询指定集合中的所有数据
func (dc *DebugController) QueryAllDataFromCollection(ctx context.Context, collectionName string) ([]map[string]interface{}, error) {
	// 获取 WxCloud 工厂
	factory, err := wxcloud.GetWxCloudFactory(nil, nil)
	if err != nil {
		return nil, fmt.Errorf("failed to get wxcloud factory: %w", err)
	}

	// 获取 WxCloud 客户端
	wxcloudFactory := factory.(*wxcloud.WxCloudFactory)
	wxcloudClient := wxcloudFactory.GetWxCloudClient()

	// 调用 database.go 中的函数查询数据
	results, err := wxcloudClient.QueryCollectionAllData(ctx, collectionName)
	if err != nil {
		return nil, fmt.Errorf("failed to query collection data: %w", err)
	}

	return results, nil
}

// GetCollectionDataHandler HTTP 处理器，用于通过 API 查询集合数据
func (dc *DebugController) GetCollectionDataHandler(c *gin.Context) (interface{}, error) {
	collectionName := c.Query("collection")

	if collectionName == "" {
		return nil, errors.New(http.StatusBadRequest, "collection name is required")
	}

	// 查询数据
	data, err := dc.QueryAllDataFromCollection(c, collectionName)
	if err != nil {
		return nil, errors.New(http.StatusInternalServerError, "failed to query collection data")
	}

	return data, nil
}
